﻿#include"XQTitleBarWidget.h"
#include<QPushButton>
#include<QBoxLayout>

void XQTitleBarWidget::setButtons(int types)
{
	int nSel = 0;//索引
	for (auto& t : m_typeAll)
	{
		if (types & t.type())//这个按钮我需不需要设置
		{
			if (m_buttons.find(& t) == m_buttons.end())//如果不存在我就新建一个
			{
				auto btn = new QPushButton(this);
				btn->setObjectName(t.objectName());
				connect(btn, &QPushButton::pressed, this, t.func());
				m_buttons[&t] = btn;
				/*m_LPTBWTypes[t.type()] = &t;*/
			}
			m_layoutBtn->insertWidget(nSel, m_buttons[&t]);
			++nSel;
		}
		else if (m_buttons.find(&t) != m_buttons.end())
		{
			layout()->removeWidget(m_buttons[&t]);
			disconnect(m_buttons[&t], &QPushButton::pressed, this, t.func());
			m_buttons[&t]->deleteLater();
			/*m_LPTBWTypes.remove(t.type());*/
			m_buttons.remove(&t);
		}
	}
	m_types = types;
	resizeEvent(nullptr);//调用事件函数设置窗口大小
}
void XQTitleBarWidget::setButtons(const QList<XQTBWType::Type>& types)
{
	//decltype(m_buttons) buttons=m_buttons;//现有的按钮
	//先删除多余的按钮
	for (auto it=m_buttons.begin();it!= m_buttons.end();)
	{
		if (types.indexOf(it.key()->type()) == -1)//需要的按钮里没有，原先的多余了删除掉
		{
			layout()->removeWidget(it.value());//从布局中删除
			disconnect(it.value(), &QPushButton::pressed, this, it.key()->func());//解除绑定
			it.value()->deleteLater();//释放按钮
			m_types &= ~it.key()->type();
			it=m_buttons.erase(it);//删除指针
		}
		else
		{
			it++;
		}
	}
	int nSel = 0;//索引
	//调整现有的顺序并且插入没有的
	for (auto& newType: types)
	{
		auto LPTBWType = std::find_if(m_typeAll.begin(), m_typeAll.end(), [=](XQTBWType type) {return type.type() == newType; });
		if (LPTBWType == nullptr)
			return;
		if (!(newType & m_types))//如果不存在我就新建一个
		{
			auto btn = new QPushButton(this);
			btn->setObjectName(LPTBWType->objectName());
			connect(btn, &QPushButton::pressed, this, LPTBWType->func());
			m_buttons[LPTBWType] = btn;
			m_types |= newType;
		}
		m_layoutBtn->insertWidget(nSel, m_buttons[LPTBWType]);
		++nSel;
	}
}